/*
 * @Author: C.
 * @Date: 2023-11-30 15:48:19
 */
import { computed, nextTick, ref, unref, watch } from 'vue'
import { dataSynchronization, paramsAdapter } from '../utils/adapter'
import { form2Filter } from '../utils/handleFilter'
export function useListFilter(
  props: Recordable,
  {
    setParams,
    load,
    setFieldsValue,
    getParams,
    reset,
    getFieldsValue,
  }: Recordable
) {
  const filterMenuList = ref<any[]>([])
  const filterRef = ref()
  watch(
    () => unref(props).formSchema,
    (v) => {
      filterMenuList.value = form2Filter(v)
    }
  )
  function handleConfirm(v: any) {
    setParams(paramsAdapter(v))
    load()
  }
  function handleClose() {
    //
  }
  function handleOpen(v: any) {
    if (filterMenuList.value.length - 1 !== v) return
    nextTick(() => {
      setFieldsValue(getParams())
    })
  }
  // 插槽表单确定
  async function formConfirm() {
    const data = await getFieldsValue()
    setParams(data)
    //同步表单数据
    dataSynchronization(data, filterMenuList.value)
    load()
    filterRef.value?.handlePopupHide()
  }
  // 插槽表单重置
  function formReset() {
    reset()
  }
  const getFilterBind = computed(() => {
    return {
      duration: 300,
      fixedTop: true,
      menuActiveText: false,
      onConfirm: handleConfirm,
      onClose: handleClose,
      onOpen: handleOpen,
      fixedTopValue: 100,
    }
  })
  return {
    getFilterBind,
    filterMenuList,
    filterRef,
    formConfirm,
    formReset,
  }
}
